# -*- coding:utf-8 -*-
import re
import urllib
import logging

from google.appengine.ext import db

import AppEnv
import Blog

__all__ = ['Tag',]

class Tag(db.Model):
    owner = db.ReferenceProperty(Blog.Blog, required=True)
    name = db.StringProperty(required=True)
    link = db.StringProperty(required=True)
    count = db.IntegerProperty(required=True)

def split_tags(s):
    s=s.replace('，',',')
    tags = list(set([k for k in [t.strip() for t in re.split('[，,;\\/\\\\]*', s)] if k != '']))
    return tags

def updateTags(blog, old, new):
    """update blog's tags based on old tag list and new tag list.
    tags in old and new must be unicode.
    """
    for t in set(new)-set(old):
        tag = Tag.all().filter('owner = ', blog).filter('name = ', t).fetch(1)
        if tag:
            tag = tag[0]
            tag.count += 1
        else:
            tag = Tag(owner = blog, name=t, link=urllib.quote_plus(t.encode(AppEnv.appencoding)), count=1)
            blog.updateTag(1)
        tag.put()
    for t in set(old)-set(new):
        tag = Tag.all().filter('owner = ', blog).filter('name = ', t).fetch(1)
        if tag:
            tag = tag[0]
            tag.count -= 1
            if tag.count <= 0:
                blog.updateTag(-1)
                tag.delete()
            else:
                tag.put()

def getTaglist(owner=None):
    fetcher = Tag.all()
    if owner:
        fetcher = fetcher.filter('owner = ',owner)
    return fetcher.fetch(limit=1000)
